package se.topshelf.golftracker.core.domain;

import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
 */
@Entity
@Table(name = "Manufacturer", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})})
public class Manufacturer extends BaseEntity implements Comparable<Manufacturer> {
    @NotNull
    private String code;
    @NotNull
    private String name;

    @NotNull
    @OneToMany(mappedBy = "manufacturer")
    @Sort(type = SortType.NATURAL)
    private SortedSet<ClubModel> clubModels = new TreeSet<ClubModel>();

    public Manufacturer() {
    }

    public Manufacturer(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public SortedSet<ClubModel> getClubModels() {
        return clubModels;
    }

    public void addClubModel(ClubModel clubModel) {
        if (clubModels.contains(clubModel)) {
            throw new IllegalArgumentException();
        }

        clubModels.add(clubModel);
        clubModel.setManufacturer(this);
    }

    void setClubModels(SortedSet<ClubModel> clubModels) {
        this.clubModels = clubModels;
    }

    @Override
    public String getGuiDescription() {
        return MessageFormat.format("{0} ({1})", name, code);
    }

    public int compareTo(Manufacturer o) {
        return name.compareTo(o.getName());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Manufacturer continent = (Manufacturer) o;

        if (!name.equals(continent.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Manufacturer");
        sb.append("{code='").append(code).append('\'');
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
